// 初始化进攻

import KTable from '@kernel/util/table'
import KUi from '@kernel/util/ui'
import KPlayerGroup from '@kernel/util/player_group'
import UI from '@data/ui'
import RectAttack from '@kernel/lib/attack/RectAttack'
import KPlayer from '@kernel/util/player'
import KRect from '@kernel/util/rect'

// 进攻间隔，秒数
const interval = 3

// 当前波数
let attackIndex = 0

// 每波怪物数量
const monsterCount = 30

// 刷怪点
const rects = [
  10003,
  10004,
  10005,
  10006,
]

// 进攻怪
const table = new KTable('进攻怪')

/**
 * 设置进攻倒计时文本
 * @param text
 */
const setAttackTime = (text: string) => {
  KPlayerGroup.fromPlaying().forEach(player => {
    let ui: KUi
    const key = 'ui-进攻倒计时'
    if (! player.hasData(key)) {
      ui = KUi.searchPath(player, UI.AttackTimerLabel)
      player.setData(key, ui)
    } else {
      ui = player.getData<KUi>(key)
    }
    ui.setText(text)
  })
}

const startAttack = () => {
  const player = KPlayer.fromId(5)
  const typeId = table.get<number>([attackIndex, 'type'])
  const attack = new RectAttack(player, typeId, monsterCount)
  rects.forEach(rect => {
    attack.addRect(new KRect(rect))
  })
  attack.onRefresh((unit) => {
    unit.setAlarmRange(999999)
    unit.setCancelAlarmRange(999999)
  })
  attack.setTarget(0, 0)
  attack.start()
}

const delayAttack = (time: number) => {
  let i = time
  const timerId = setInterval(() => {
    i--
    if (i <= 0) {
      attackIndex++
      startAttack()
      clearInterval(timerId)
      setAttackTime(`第${attackIndex}波进攻`)
    } else {
      setAttackTime(`${i}秒后开始进攻`)
    }
  }, 1000)
}

const InitAttack = () => {
  delayAttack(interval)
}

export default InitAttack
